const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: '[name].[contenthash:6].js',
    path: path.resolve(__dirname, '..', 'dist')
  },
  resolve: {
    // 路径别名
    alias: {
      '@': path.resolve('src')
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'webpack-demo',
      template: 'public/index.html'
    })
  ],
  module: {
    rules: [
      {
        test: /\.(jpg|png|svg)$/i,
        type: 'asset',
        exclude: path.resolve(__dirname, '..', 'src/assets/icons/svg')
      },
      {
        test: /\.svg$/i,
        include: path.resolve(__dirname, '..', 'src/assets/icons/svg'),
        use: [
          {
            loader: 'svg-sprite-loader',
            options: {
              symbolId: filePath => {
                let name = path.basename(filePath, '.svg');
                const p = /[\\/]svg[\\/](.+)[\\/]/.exec(filePath);
                if (p && p[1]) {
                  name = p[1].trim().replace(/[\\/]/g, '-') + '-' + name;
                }
                return 'icon-' + name;
              }
            }
          }
        ]
      },
      {
        test: /\.css$/i,
        include: /src/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.less$/i,
        include: /src/,
        use: ['style-loader', 'css-loader', 'less-loader']
      },
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [['@babel/preset-env', { targets: 'defaults' }]]
          }
        }
      }
    ]
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        async: {
          name: 'chunk-async',
          chunks: 'async',
          reuseExistingChunk: true,
          priority: 5
        },
        vendors: {
          name: 'chunk-vendors',
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        common: {
          name: 'chunk-common',
          minChunks: 2,
          chunks: 'initial',
          priority: -20
        }
      }
    },
    runtimeChunk: {
      name: entrypoint => `runtime-${entrypoint.name}`
    }
  },
  performance: { hints: false }
};
